/* 
    错误日志上报2.0
    参数说明:
    base: 公共基础参数
    base.title: 页面标题
    base.userAgent: 用户设备浏览器信息
    base.logTime: 日志时间
    base.os: 系统h5
    base.appVer: 版本号
    base.webId: 设备号
    base.token: 用户token 
    base.uid: 用户id
    base.netType: 网络状态
    base.sysVer: '',
    base.imei: '',
    base.uuid: 设备号
    base.deviceId: 设备号
    base.chan: 来源
    base.appType: app类型4为淘集集
    base.traceId: '',
    base.sessionId: 回话id
    base.logType: 日志类型5
    base.cuid: 设备号
    base.login_mode: 登录方式
    logLevel: 错误等级1,2,3,4后两级报警通知
    errType: 错误类型 11为代码报错，12为资源报错，21为api参数报错，21为api其他报错
    apiError： 错误详情信息
    apiError.message： 错误描述信息
    apiError.uri： 错误页面链接
    apiError.apiUri: 错误的api链接
    apiError.data: api错误返回的完整数据
    apiError.method: api错误的请求方式
    apiError.code: api错误或资源报错的状态码
    apiError.params: api错误的完整入参
*/
// import {getNetworkType} from '@/utils/mUtils'

(function (win) {
    var winIsOnLoad = false;
    var sourceErrNum = 0;
    var sourceArr = [];
    win.TJJ_BUGCOLLECT = [];

    var TJJERRORLOG = {
        u: navigator.userAgent, //用户设备信息
        os: '', //操作系统
        actType: 0,
        tjj_actRegObj: { //活动区分
            '(fissile.taojiji)|(fissile.tjjshop)|(wap.taojiji)|(fission.tjjshop)': 1,
            'growth': 2,
            '(a.taojiji)|(a.tjjshop)': 3
        },
        init: function () {
            this.os = this.u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/) ? 'ios' : this.u.indexOf('Android') >
                -1 || this.u.indexOf('Linux') > -1 ? 'android' : '';
            this.filterAct();
        },
        filterAct: function () {
            for (var key in this.tjj_actRegObj) {
                var href = location.href;
                var _reg = new RegExp(key);
                var temp = _reg.test(href);
                if (temp) {
                    this.actType = this.tjj_actRegObj[key];
                    this.actType == 1 ? (href.indexOf('super/view') > -1 ? this.actType = 2 : '') : '';
                }
            }
        },
        errorListener: function (event) {
            var _target = event.target;
            var _nodeName = _target.nodeName ? _target.nodeName.toLowerCase() : '';
            console.log(_nodeName)
            if (_nodeName == 'script' || _nodeName == 'link' || _nodeName == 'img') { //资源加载报错
                var _src = _target.src || _target.href;
                this.sourceTest(_target, _src)
            } else if (winIsOnLoad) {
                errorLogUpload({
                    logLevel: 4,
                    errType: 12,
                    apiError: {
                        uri: event.target.baseURI || location.href,
                        message: (event.error && event.error.stack) || event.message || event.type +
                            ' in ' + event.target.outerHTML,
                    }
                })
            } else {
                win.TJJ_BUGCOLLECT.push({
                    message: (event.error && event.error.stack) || event.message || event.type +
                        ' in ' + event.target.outerHTML,
                    uri: event.target.baseURI || location.href,
                })
            }
            console.log(event)
        },
        sourceTest: function (target, src) {
            if (!src || !win.XMLHttpRequest) return;
            sourceErrNum++;
            var self = this;
            var xhr = new XMLHttpRequest;
            xhr.open("GET", src);
            xhr.send();
            xhr.onload = function (e) {
                console.log(e.target.status)
                if (e.target.status != 200) { // 资源非正常
                    self.sourceErrAdd(e.target.status, target.outerHTML)
                }
            }
            xhr.onerror = function (e) {
                self.sourceErrAdd(e.target.status, target.outerHTML)
            }
        },
        sourceErrAdd: function (code, ele) {
            sourceArr.push('resourceError: ' + code + ' in ' + ele);
            sourceErrNum--;
            if (sourceErrNum < 1) {
                console.log('source 上报')
                errorLogUpload({
                    logLevel: 4,
                    errType: 12,
                    apiError: {
                        uri: location.href,
                        message: sourceArr.join(' && ')
                    }
                });
                sourceArr = [];
                sourceErrNum = 0;
            }
        },
        // 获取url参数(&符号拼接参数)
        getQueryString: function (name) {
            var reg = new RegExp("(^|&)" + name + "=([^&]*)", "ig");
            var r;
            r = win.location.search.substr(1).match(reg);
            r == 'null' || r == 'undefined' ? r = null : '';
            if (r) {
                var val = r[r.length - 1].split('=')[1];
                return val == 'null' || val == 'undefined' ? null : val;
            }
            // if (r) return unescape(r[2]);
            r = this.getParams(name);
            r == 'null' || r == 'undefined' ? r = null : '';
            if (r) return r;
            return null;
        },
        // 获取url参数(/符号拼接参数)
        getParams: function (key) {
            var url = win.location.pathname;
            var arr = url.split('/');
            var index = arr.lastIndexOf(key);
            return (index < 0 ? null : arr[index + 1]);
        },
        // 获取网络状态
        getNetWork: function () {

            var userAgent = navigator.userAgent,
                sys = "",
                ipod = userAgent.match(/(ipod).*\s([\d_]+)/i),
                ipad = userAgent.match(/(ipad).*\s([\d_]+)/i),
                iphone = userAgent.match(/(iphone)\sos\s([\d_]+)/i),
                android = userAgent.match(/(android)\s([\d\.]+)/i);
            sys = "Unknown",
                android ? sys = "Android " + android[2] : iphone ? sys = "iPhone, iOS " + iphone[2].replace(
                    /_/g, ".") : ipad ? sys = "iPad, iOS " + ipad[2].replace(/_/g, ".") : ipod && (sys =
                    "iPod, iOS " + ipod[2].replace(/_/g, "."));
            var net = sys,
                l = userAgent.match(/MicroMessenger\/([\d\.]+)/i);
            sys = "Unknown",
                l && l[1] ? (sys = l[1],
                    net += ", WeChat " + sys) : '',
                sys = "Unknown",
                net = sys;
            console.log(net);


            var networkStr = navigator.userAgent.match(/NetType\/\w+/) ? navigator.userAgent.match(
                /NetType\/\w+/)[0] : 'NetType/'; //网络状态
            networkStr = networkStr.toLowerCase().replace('nettype/', ''); //网络状态
            var connection = navigator.connection || navigator.mozConnection || navigator.webkitConnection ||
                {
                    tyep: 'unknown'
                };
            var netWorkType = connection.type;
            return networkStr || netWorkType || 'unknown'
        }
    }

    TJJERRORLOG.init();

    win.addEventListener('error', function (event) {
        TJJERRORLOG.errorListener(event);
    }, true)

    //首次进入系统，加载完成后执行
    win.onload = function () {
        if (TJJ_BUGCOLLECT.length > 0) {
            self.errorLogUpload({
                logLevel: 4,
                errType: 11,
                codeError: {
                    message: (function () {
                        var _msg = '';
                        var _len = TJJ_BUGCOLLECT.length
                        TJJ_BUGCOLLECT.map(function (item, index) {
                            index >= _len - 1 ? _msg += item.message : _msg += item.message +
                                ' && ';
                        })
                        return _msg
                    })(),
                    uri: TJJ_BUGCOLLECT[0].uri
                }
            });
        }
    };

    // 错误上报
    win.errorLogUpload = function (obj) {
        console.log(obj)
        var networkStr = ''; //网络状态
        var uuid = TJJERRORLOG.getQueryString('uuid') || '';
        var xhr = new XMLHttpRequest();
        var params = {
            actType: TJJERRORLOG.actType,
            base: {
                title: document.title || '',
                userAgent: TJJERRORLOG.u || '',
                logTime: new Date().getTime() || '', // 日志时间
                os: TJJERRORLOG.os ? TJJERRORLOG.os + '-h5' : 'h5',
                appVer: TJJERRORLOG.getQueryString('version') || '',
                webId: uuid, //设备号
                token: TJJERRORLOG.getQueryString('token') || '',
                uid: TJJERRORLOG.getQueryString('user_id') || '', //用户id
                netType: networkStr || '', // 网络状态
                sysVer: '',
                imei: '',
                uuid: uuid,
                deviceId: uuid,
                chan: 'h5',
                appType: 4,
                traceId: '',
                sessionId: TJJERRORLOG.getQueryString('sessionid') || TJJERRORLOG.getQueryString(
                    'session_id') || '',
                logType: 5,
                cuid: uuid,
                login_mode: '',

            }
        };
        for (var key in obj) {
            params[key] = obj[key];
        }
        // console.log('报错：', JSON.stringify(params))
        // var _postUrl = location.href.indexOf('taojiji.com') > -1 ?
        //     'https://fissile.taojiji.com/safety.php/index/pageLog' :
        //     'https://fissile.tjjshop.cn/safety.php/index/pageLog';
        var _postUrl = window.location.host == 'mstatic.shandjj.com' ? 'https://h5-app-log.ayouxing.com/web/log' : 'http://h5-app-log.sdjjia.com:8031/web/log';
            
        xhr.open("POST", _postUrl, true);
        //设置发送数据的请求格式
        // xhr.setRequestHeader('content-type', 'application/json');
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 304)) {
                console.log('上报成功!');
            }
        }
        //将用户输入值序列化成字符串
        xhr.send(JSON.stringify(params));
    }

})(window)